import { useEffect, useState } from 'react';
import { FilterSidebar } from '../components/FilterSidebar';
import { ProductCard } from '../components/ProductCard';
import { Pagination } from '../components/Pagination';
import { Filter, X } from 'lucide-react';
import { setPageTitle } from '../lib/utils';

export function Makeup() {
  const [currentPage, setCurrentPage] = useState(1);
  const [showFilters, setShowFilters] = useState(false);
  const [selectedFilters, setSelectedFilters] = useState<Record<string, string[]>>({});
  const [filteredProducts, setFilteredProducts] = useState<any[]>([]);
  const productsPerPage = 9;
  // Mock makeup products data
  const products = [{
    id: 'mk-001',
    title: 'Natural Finish Foundation',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1625093742435-6fa192b6fb10?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.7,
    reviewCount: 82,
    price: 42.0,
    category: 'Makeup',
    type: 'foundation',
    finish: 'natural',
    coverage: 'medium'
  }, {
    id: 'mk-002',
    title: 'Tinted Lip Balm',
    brand: 'Pure Bloom',
    image: 'https://images.unsplash.com/photo-1586495777744-4413f21062fa?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.9,
    reviewCount: 67,
    price: 24.0,
    category: 'Makeup',
    type: 'lip',
    finish: 'glossy',
    coverage: 'sheer'
  }, {
    id: 'mk-003',
    title: 'Cream Blush',
    brand: 'Ritual Beauty',
    image: 'https://images.unsplash.com/photo-1596462502278-27bfdc403348?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.8,
    reviewCount: 53,
    price: 32.0,
    category: 'Makeup',
    type: 'blush',
    finish: 'dewy',
    coverage: 'buildable'
  }, {
    id: 'mk-004',
    title: 'Lengthening Mascara',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1512496015851-a90fb38ba796?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.6,
    reviewCount: 91,
    price: 28.0,
    originalPrice: 32.0,
    category: 'Makeup',
    type: 'mascara',
    finish: 'natural',
    coverage: 'buildable'
  }, {
    id: 'mk-005',
    title: 'Brow Defining Pencil',
    brand: 'Ritual Beauty',
    image: 'https://images.unsplash.com/photo-1596462502278-27bfdc403348?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.5,
    reviewCount: 48,
    price: 22.0,
    category: 'Makeup',
    type: 'brow',
    finish: 'natural',
    coverage: 'buildable'
  }, {
    id: 'mk-006',
    title: 'Cream Eyeshadow Stick',
    brand: 'Pure Bloom',
    image: 'https://images.unsplash.com/photo-1631214540553-ff044a3ff1d4?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.7,
    reviewCount: 39,
    price: 26.0,
    category: 'Makeup',
    type: 'eye',
    finish: 'satin',
    coverage: 'buildable'
  }, {
    id: 'mk-007',
    title: 'Hydrating Concealer',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1522335789203-aabd1fc54bc9?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.8,
    reviewCount: 75,
    price: 32.0,
    category: 'Makeup',
    type: 'concealer',
    finish: 'natural',
    coverage: 'medium'
  }, {
    id: 'mk-008',
    title: 'Matte Lipstick',
    brand: 'Ritual Beauty',
    image: 'https://images.unsplash.com/photo-1503236823255-94609f598e71?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.6,
    reviewCount: 62,
    price: 28.0,
    category: 'Makeup',
    type: 'lip',
    finish: 'matte',
    coverage: 'full'
  }, {
    id: 'mk-009',
    title: 'Illuminating Highlighter',
    brand: 'Pure Bloom',
    image: 'https://www.jiomart.com/images/product/original/rvnta5emux/the-dubai-dolls-yalla-ultra-fine-illuminating-highlighter-silky-pigments-for-long-lasting-shimmer-look-suitable-for-all-skin-tone-product-images-orvnta5emux-p604583824-0-202309150231.jpg?im=Resize=(420,420)',
    rating: 4.9,
    reviewCount: 43,
    price: 34.0,
    originalPrice: 38.0,
    category: 'Makeup',
    type: 'highlighter',
    finish: 'radiant',
    coverage: 'buildable'
  }, {
    id: 'mk-010',
    title: 'Bronzing Powder',
    brand: 'Glow Theory',
    image: 'https://images.unsplash.com/photo-1596462502278-27bfdc403348?ixlib=rb-4.0.3&auto=format&fit=crop&w=800&q=80',
    rating: 4.7,
    reviewCount: 37,
    price: 36.0,
    category: 'Makeup',
    type: 'bronzer',
    finish: 'natural',
    coverage: 'buildable'
  }];
  // Filter categories
  const filterCategories = [{
    name: 'Product Type',
    options: [{
      id: 'foundation',
      label: 'Foundation'
    }, {
      id: 'concealer',
      label: 'Concealer'
    }, {
      id: 'lip',
      label: 'Lip Products'
    }, {
      id: 'eye',
      label: 'Eye Products'
    }, {
      id: 'mascara',
      label: 'Mascara'
    }, {
      id: 'brow',
      label: 'Brow Products'
    }, {
      id: 'blush',
      label: 'Blush'
    }, {
      id: 'highlighter',
      label: 'Highlighter'
    }, {
      id: 'bronzer',
      label: 'Bronzer'
    }]
  }, {
    name: 'Finish',
    options: [{
      id: 'natural',
      label: 'Natural'
    }, {
      id: 'matte',
      label: 'Matte'
    }, {
      id: 'dewy',
      label: 'Dewy'
    }, {
      id: 'glossy',
      label: 'Glossy'
    }, {
      id: 'radiant',
      label: 'Radiant'
    }, {
      id: 'satin',
      label: 'Satin'
    }]
  }, {
    name: 'Coverage',
    options: [{
      id: 'sheer',
      label: 'Sheer'
    }, {
      id: 'light',
      label: 'Light'
    }, {
      id: 'medium',
      label: 'Medium'
    }, {
      id: 'full',
      label: 'Full'
    }, {
      id: 'buildable',
      label: 'Buildable'
    }]
  }, {
    name: 'Brand',
    options: [{
      id: 'Pure Bloom',
      label: 'Pure Bloom'
    }, {
      id: 'Glow Theory',
      label: 'Glow Theory'
    }, {
      id: 'Ritual Beauty',
      label: 'Ritual Beauty'
    }]
  }];

  // Set page title
  useEffect(() => {
    setPageTitle('Makeup');
  }, []);

  // Apply filters
  useEffect(() => {
    let result = [...products];
    // Apply filters for each category
    Object.entries(selectedFilters).forEach(([category, selectedOptions]) => {
      if (selectedOptions.length > 0) {
        result = result.filter(product => {
          if (category === 'Product Type') {
            return selectedOptions.includes(product.type);
          } else if (category === 'Finish') {
            return selectedOptions.includes(product.finish);
          } else if (category === 'Coverage') {
            return selectedOptions.includes(product.coverage);
          } else if (category === 'Brand') {
            return selectedOptions.includes(product.brand);
          }
          return true;
        });
      }
    });
    setFilteredProducts(result);
    setCurrentPage(1); // Reset to first page when filters change
  }, [selectedFilters]);
  // Initialize filtered products
  useEffect(() => {
    setFilteredProducts(products);
  }, []);
  const handleFilterChange = (category: string, optionId: string) => {
    setSelectedFilters(prev => {
      const prevSelected = prev[category] || [];
      // If already selected, remove it
      if (prevSelected.includes(optionId)) {
        const updated = prevSelected.filter(id => id !== optionId);
        return {
          ...prev,
          [category]: updated
        };
      }
      // Otherwise add it
      return {
        ...prev,
        [category]: [...prevSelected, optionId]
      };
    });
  };
  const clearFilters = () => {
    setSelectedFilters({});
  };
  // Calculate pagination
  const totalPages = Math.ceil(filteredProducts.length / productsPerPage);
  const indexOfLastProduct = currentPage * productsPerPage;
  const indexOfFirstProduct = indexOfLastProduct - productsPerPage;
  const currentProducts = filteredProducts.slice(indexOfFirstProduct, indexOfLastProduct);
  const handlePageChange = (pageNumber: number) => {
    setCurrentPage(pageNumber);
    window.scrollTo(0, 0);
  };
  return <div className="max-w-7xl mx-auto px-4 md:px-8 lg:px-12 py-12">
      <div className="mb-8">
        <h1 className="font-serif text-3xl md:text-4xl text-[#4a4a4a] mb-4">
          Makeup
        </h1>
        <p className="text-sm md:text-base max-w-3xl">
          Discover our collection of clean, high-performance makeup that
          enhances your natural beauty. From lightweight foundations to
          nourishing lip products, each item is designed to make you feel
          beautiful inside and out.
        </p>
      </div>
      {/* Mobile filter button */}
      <div className="md:hidden mb-6">
        <button onClick={() => setShowFilters(true)} className="w-full flex items-center justify-center space-x-2 bg-white border border-[#e8e5e0] py-3 rounded-md">
          <Filter size={18} />
          <span>Filter Products</span>
        </button>
      </div>
      {/* Mobile filter drawer */}
      {showFilters && <div className="md:hidden">
          <FilterSidebar categories={filterCategories} selectedFilters={selectedFilters} onFilterChange={handleFilterChange} onClearFilters={clearFilters} isMobile={true} onClose={() => setShowFilters(false)} />
        </div>}
      <div className="flex flex-col md:flex-row gap-8">
        {/* Desktop Sidebar */}
        <div className="hidden md:block w-64 flex-shrink-0">
          <FilterSidebar categories={filterCategories} selectedFilters={selectedFilters} onFilterChange={handleFilterChange} onClearFilters={clearFilters} />
        </div>
        {/* Product Grid */}
        <div className="flex-1">
          {/* Active filters */}
          {Object.entries(selectedFilters).some(([_, values]) => values.length > 0) && <div className="mb-6 flex flex-wrap gap-2 items-center">
              <span className="text-sm font-medium">Active Filters:</span>
              {Object.entries(selectedFilters).map(([category, values]) => values.map(value => {
            // Find the label for this value
            const filterCategory = filterCategories.find(c => c.name === category);
            const option = filterCategory?.options.find(o => o.id === value);
            return <div key={`${category}-${value}`} className="flex items-center bg-[#f3f0eb] px-3 py-1 rounded-full text-sm">
                      <span>{option?.label || value}</span>
                      <button onClick={() => handleFilterChange(category, value)} className="ml-2 text-[#4a4a4a]" aria-label={`Remove ${option?.label || value} filter`}>
                        <X size={14} />
                      </button>
                    </div>;
          }))}
              <button onClick={clearFilters} className="text-sm text-[#4a6b60] hover:underline">
                Clear All
              </button>
            </div>}
          {/* Results count and sort */}
          <div className="flex justify-between items-center mb-6">
            <p className="text-sm">
              Showing {indexOfFirstProduct + 1}-
              {Math.min(indexOfLastProduct, filteredProducts.length)} of{' '}
              {filteredProducts.length} products
            </p>
            <div className="flex items-center">
              <label htmlFor="sort" className="text-sm mr-2">
                Sort by:
              </label>
              <select id="sort" className="text-sm border border-[#e8e5e0] rounded-md px-2 py-1 focus:outline-none focus:border-[#4a6b60]">
                <option value="featured">Featured</option>
                <option value="newest">Newest</option>
                <option value="price-low">Price: Low to High</option>
                <option value="price-high">Price: High to Low</option>
                <option value="rating">Top Rated</option>
              </select>
            </div>
          </div>
          {/* Products grid */}
          {currentProducts.length > 0 ? <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
              {currentProducts.map(product => <ProductCard key={product.id} id={product.id} title={product.title} brand={product.brand} image={product.image} rating={product.rating} reviewCount={product.reviewCount} price={product.price} originalPrice={product.originalPrice} category={product.category} />)}
            </div> : <div className="text-center py-12">
              <p className="text-lg font-serif mb-2">No products found</p>
              <p className="text-sm text-gray-500 mb-6">
                Try adjusting your filters to find what you're looking for.
              </p>
              <button onClick={clearFilters} className="bg-[#4a6b60] hover:bg-[#3d5a50] text-white px-6 py-3 rounded-md transition-colors">
                Clear All Filters
              </button>
            </div>}
          {/* Pagination */}
          {filteredProducts.length > productsPerPage && <Pagination currentPage={currentPage} totalPages={totalPages} onPageChange={handlePageChange} />}
        </div>
      </div>
    </div>;
}